package ph.com.gs3.chat.fragments.worker;

import java.util.ArrayList;
import java.util.List;

import ph.com.gs3.chat.communicators.HttpCommunicator;
import ph.com.gs3.chat.communicators.UserCommunicatorModule;
import ph.com.gs3.chat.fragments.interfaces.CallbackCommand;
import ph.com.gs3.chat.managers.UserManager;
import ph.com.gs3.chat.managers.UserManager.UserDownloadFailedException;
import ph.com.gs3.chat.managers.UserManager.UserParseException;
import ph.com.gs3.chat.model.valueobject.business.User;
import ph.com.gs3.chat.model.valueobject.business.UserStub;
import android.app.Fragment;
import android.os.AsyncTask;

public class MainWorkerFragment extends Fragment {

	public static final String TAG = MainWorkerFragment.class.getSimpleName();

	// fields
	private User currentlyActiveUser;

	private UserManager userManager;

	// required empty constructor
	public MainWorkerFragment() {}

	// Builder
	public static MainWorkerFragment createInstance(User currentlyActiveUser) {

		MainWorkerFragment instance = new MainWorkerFragment();
		instance.currentlyActiveUser = currentlyActiveUser;

		instance.initializeManager();

		return instance;

	}

	private void initializeManager() {

		// manager dependencies
		HttpCommunicator communicator = new HttpCommunicator();
		String server = currentlyActiveUser.getAccountServer();
		UserCommunicatorModule userCommunicatorModule = new UserCommunicatorModule(communicator,
		        server);

		userManager = new UserManager(userCommunicatorModule);

	}

	public User getCurrentlyActiveUser() {
		return currentlyActiveUser;
	}

	public void getOnlineUsers(final CallbackCommand<List<UserStub>> callback) {

		AsyncTask<Void, Void, List<UserStub>> task = new AsyncTask<Void, Void, List<UserStub>>() {

			@Override
			protected List<UserStub> doInBackground(Void... params) {

				List<UserStub> onlineUsers = new ArrayList<>();

				try {
					onlineUsers = userManager.getOnlineUsers(currentlyActiveUser);
				} catch (UserDownloadFailedException | UserParseException e) {
					e.printStackTrace();
				}

				return onlineUsers;
			}

			@Override
			protected void onPostExecute(List<UserStub> result) {
				super.onPostExecute(result);

				if (callback != null) {
					callback.execute(result);
				}

			}

		};

		task.execute();

	}

}
